package common.liusany.admin.service.account;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.Md5CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import common.liusany.admin.entity.account.Group;
import common.liusany.admin.entity.account.User;
import common.liusany.admin.service.security.CaptchaUsernamePasswordToken;
import common.liusany.admin.service.security.IncorrectCaptchaException;
import com.octo.captcha.service.CaptchaService;

public class ShiroDbRealm extends AuthorizingRealm {

	private AccountManager accountManager;
	@Resource
	private CaptchaService captchaService;
	
	 public ShiroDbRealm() {
//	        setCredentialsMatcher(new Sha256CredentialsMatcher());
//	        setCredentialsMatcher(new Md5CredentialsMatcher());
	    }
	 
	/**
	 * 认证回调函数, 登录时调用.
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = accountManager.findUserByLoginName(token.getUsername());
		if (user != null) {
			return new SimpleAuthenticationInfo(user.getLoginName(),
					user.getPassword(), getName());
		} else {
			return null;
		}
	}
	 
	/**
	 * 校验验证码.
	 * @param token 认真令牌
	 * @return
	 */
	protected boolean validateCaptcha(CaptchaUsernamePasswordToken token) {
		String captchaID = (String) SecurityUtils.getSubject().getSession().getId();
		String challengeResponse = StringUtils.upperCase(token.getCaptcha());
		return captchaService.validateResponseForID(captchaID, challengeResponse);
	}
		
//	/**
//	 * 认证回调函数, 登录时调用.
//	 */
//	protected AuthenticationInfo doGetAuthenticationInfo(
//			AuthenticationToken authcToken) throws AuthenticationException {
//		
//		CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;
//		boolean isCaptcha = validateCaptcha(token);
//		if(!isCaptcha){
//			throw new IncorrectCaptchaException("验证码错误.");
//		}
//		User user = accountManager.findUserByLoginName(token.getUsername());
//		if (user != null) {
//			System.out.println("用户存在"+"用户名:"+user.getLoginName()+"密码"+user.getPassword());
//			return new SimpleAuthenticationInfo(user.getLoginName(),
//					user.getPassword(), getName());
//		} else {
//			return null;
//		}
//	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		
		System.out.println("授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.");
		
		
		String loginName = (String) principals.fromRealm(getName()).iterator()
				.next();
		User user = accountManager.findUserByLoginName(loginName);
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			for (Group group : user.getGroupList()) {
				info.addRole(group.getName());
				info.addStringPermissions(group.getPermissionList());
			}
			return info;
		} else {
			return null;
		}
	}

	/**
	 * 更新用户授权信息缓存.
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}
}
